<?php
//自动生成,请根据需要修改
namespace app\redenvelope\controller;
use app\common\controller\Base;
use think\Exception;
use think\facade\Request;
use think\Db;
use think\Validate;

/**
* @title 发出红包列表接口
* @description 发出红包列表说明
* @group 红包
*/
class RedSend extends Base
{

    /**
     * @title 插入记录
     * @description 插入发出红包列表数据
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/add
     * @method post
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:amount type:Int require:0 default:0 other: desc:金额
     * @param name:message type:VarChar require:0 default:0 other: desc:留言
     * @param name:send_time type:Int require:0 default:0 other: desc:发出红包的时间
     * @param name:red_type type:VarChar require:0 default:0 other: desc:红包的类型
     * @param name:account_id type:VarChar require:0 default:0 other: desc:发送人
     * @param name:can_rob type:decimal require:0 default:0 other: desc:红包可抢
     * @param name:num type:Int require:0 default:0 other: desc:红包的个数
     *
     *
     * @return amount:金额
     * @return message:留言
     * @return send_time:发出红包的时间
     * @return red_type:红包的类型
     * @return account_id:发送人
     * @return can_rob:红包可抢
     * @return num:红包的个数
     *
     */
    public function add()
    {
        //模块 - 输入数据
        $input['amount'] = Request::post('amount');
        $input['message'] = Request::post('message');
        $input['send_time'] = Request::post('send_time/d');
        $input['red_type'] = Request::post('red_type');
        $input['account_id'] = Request::post('account_id/d');
        $input['can_rob'] = Request::post('can_rob');
        $input['num'] = Request::post('num/d');


        //模块 - 验证器
        $red_sendValidate = new \app\redenvelope\validate\RedSend;
        $validate = $red_sendValidate->scene('except_id')->check($input);
        if (!$validate) {
            $msg['msg'] = '验证失败';
            $msg['validate'] = $red_sendValidate->getError();
            return $this->errorJson($msg);
        }

        // ---	模块 - 新增  ---
        //插入的数据
        $insert_data = [
            'amount' => $input['amount'],
            'message' => $input['message'],
            'send_time' => $input['send_time'],
            'red_type' => $input['red_type'],
            'account_id' => $input['account_id'],
            'can_rob' => $input['can_rob'],
            'num' => $input['num'],
        ];
        //添加数据
        $insert_res = Db::name('red_send')->data($insert_data)->insert();
        if (!$insert_res) {
            $msg['msg'] = '插入数据失败！';
            return $this->errorJson($msg);
        }
        $msg['res'] = $insert_res;


        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 获取列表数据（paginate）
     * @description 获取发出红包列表的列表数据（分页）
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/get_list
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:Int require:1 default:0 other: desc:id
     * @param name:amount type:Int require:0 default:0 other: desc:金额
     * @param name:message type:VarChar require:0 default:0 other: desc:留言
     * @param name:send_time type:Int require:0 default:0 other: desc:发出红包的时间
     * @param name:red_type type:VarChar require:0 default:0 other: desc:红包的类型
     * @param name:account_id type:Int require:0 default:0 other: desc:发送人
     * @param name:can_rob type:decimal require:0 default:0 other: desc:红包可抢
     * @param name:num type:Int require:1 default:0 other: desc:红包的个数
     *
     * @param name:page type:Int require:0 default:0 other: desc:当前页
     * @param name:pagesize type:Int require:0 default:0 other: desc:每页数量
     *
     * @return id:id
     * @return amount:金额
     * @return message:留言
     * @return send_time:发出红包的时间
     * @return red_type:红包的类型
     * @return account_id:发送人
     * @return can_rob:红包可抢
     * @return num:红包的个数
     *
     */
    public function get_list()
    {
        //模块 - 输入数据
        $input['id'] = Request::param('id/d');
        $input['amount'] = Request::param('amount');
        $input['message'] = Request::param('message');
        $input['send_time'] = Request::param('send_time/d');
        $input['red_type'] = Request::param('red_type');
        $input['account_id'] = Request::param('account_id/d');
        $input['can_rob'] = Request::param('can_rob');
        $input['num'] = Request::param('num/d');


        // ---	模块 - 查询  ---
        //查询条件
        $temp_map = [
            ['id', '=', $input['id']],
            ['amount', '=', $input['amount']],
            ['message', 'like', '%' . $input['message'] . '%'],
            ['send_time', '=', $input['send_time']],
            ['red_type', 'like', '%' . $input['red_type'] . '%'],
            ['account_id', '=', $input['account_id']],
            ['can_rob', '=', $input['can_rob']],
            ['num', '=', $input['num']],
        ];
        //去除为空的条件
        $paginate_map = [];
        foreach ($temp_map as $k => $v) {
            if ($v[2] === null || $v[2] == '' || $v[2] == '%%') {
                continue;
            }
            array_push($paginate_map, $v);
        }

        //获取数据
        $select_res = Db::name('red_send')->where($paginate_map)->paginate();

        // paginate 返回数据
        $msg['list'] = $select_res;


        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 获取列表数据（select）
     * @description 获取发出红包列表的列表数据（无分页）
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/get_select
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:Int require:0 default:0 other: desc:id
     * @param name:amount type:Int require:0 default:0 other: desc:金额
     * @param name:message type:VarChar require:0 default:0 other: desc:留言
     * @param name:send_time type:Int require:0 default:0 other: desc:发出红包的时间
     * @param name:red_type type:VarChar require:0 default:0 other: desc:红包的类型
     * @param name:account_id type:VarChar require:1 default:0 other: desc:发送人
     * @param name:can_rob type:decimal require:0 default:0 other: desc:红包可抢
     * @param name:num type:Int require:0 default:0 other: desc:红包的个数
//     * @param name:res_money type:Int require:0 default:0 other: desc:剩余金额
//     * @param name:res_num type:Int require:0 default:0 other: desc:剩余数量
     * @param name:logo type:VarChar require:0 default:0 other: desc:头像
     *
     *
     * @return id:id
     * @return amount:金额
     * @return message:留言
     * @return send_time:发出红包的时间
     * @return red_type:红包的类型
     * @return account_id:发送人
     * @return can_rob:红包可抢
     * @return res_num:剩余数量
     * @return res_money:剩余金额
     * @return num:红包的个数
     * @return logo:头像
     * @return rob_status:红包是否抢完
     *
     *
     */
    public function get_select()
    {
        //模块 - 输入数据
        $input['id'] = Request::param('id/d');
        $input['amount'] = Request::param('amount');
        $input['message'] = Request::param('message');
        $input['send_time'] = Request::param('send_time/d');
        $input['red_type'] = Request::param('red_type');
        $input['account_id'] = Request::param('account_id');
        $input['can_rob'] = Request::param('can_rob');
        $input['num'] = Request::param('num/d');
        $input['logo']=Request::post('logo');

        // ---	模块 - 查询  ---
        //查询条件
        $temp_map = [
            ['id', '=', $input['id']],
            ['amount', '=', $input['amount']],
            ['message', 'like', '%' . $input['message'] . '%'],
            ['logo', 'like', '%' . $input['logo'] . '%'],
            ['send_time', '=', $input['send_time']],
            ['red_type', 'like', '%' . $input['red_type'] . '%'],
            ['account_id', 'like', '%' . $input['account_id'] . '%'],
            ['can_rob', '=', $input['can_rob']],
            ['num', '=', $input['num']],

        ];
        //去除为空的条件
        $select_map = [];
        foreach ($temp_map as $k => $v) {
            if ($v[2] === null || $v[2] == '' || $v[2] == '%%') {
                continue;
            }
            array_push($select_map, $v);
        }


        //获取数据
        $select_res = Db::name('red_send')->where($select_map)->select();

        logs("sql",Db::name('red_send')->getLastSql());

        // select 返回数据
        $msg['list'] = $select_res;


        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 获取单条数据
     * @description 根据ID获取发出红包列表的指定记录
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/info
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:Int require:1 default:0 other: desc:id
     *
     *
     * @return id:id
     *
     */
    public function info()
    {
        //模块 - 输入数据
        $input['id'] = Request::param('id/d');

        // input结果返回
        $msg['data']['id'] = $input['id'];

        //模块 - 验证器
        $red_sendValidate = new \app\redenvelope\validate\RedSend;
        $validate = $red_sendValidate->scene('only_id')->check($input);
        if (!$validate) {
            $msg['msg'] = '验证失败';
            $msg['validate'] = $red_sendValidate->getError();
            return $this->errorJson($msg);
        }

        // ---	模块 - 查询  ---
        //查询条件
        $temp_map = [
            ['id', '=', $input['id']],
        ];
        //去除为空的条件
        $find_map = [];
        foreach ($temp_map as $k => $v) {
            if ($v[2] === null || $v[2] == '' || $v[2] == '%%') {
                continue;
            }
            array_push($find_map, $v);
        }

        //获取数据
        $select_res = Db::name('red_send')->where($find_map)->find();

        // find 返回数据
        $msg['data'] = $select_res;


        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 更新记录
     * @description 根据ID更新发出红包列表指定记录的数据
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/edit
     * @method post
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:Int require:1 default:0 other: desc:id
     * @param name:amount type:Int require:0 default:0 other: desc:金额
     * @param name:message type:VarChar require:0 default:0 other: desc:留言
     * @param name:send_time type:Int require:0 default:0 other: desc:发出红包的时间
     * @param name:red_type type:VarChar require:0 default:0 other: desc:红包的类型
     * @param name:account_id type:VarChar require:0 default:0 other: desc:发送人
     * @param name:can_rob type:decimal require:0 default:0 other: desc:红包可抢
     * @param name:num type:Int require:0 default:0 other: desc:红包的个数
     *
     *
     * @return id:id
     * @return amount:金额
     * @return message:留言
     * @return send_time:发出红包的时间
     * @return red_type:红包的类型
     * @return account_id:发送人
     * @return can_rob:红包可抢
     * @return num:红包的个数
     *
     */
    public function edit()
    {
        //模块 - 输入数据
        $input['id'] = Request::post('id/d');
        $input['amount'] = Request::post('amount');
        $input['message'] = Request::post('message');
        $input['send_time'] = Request::post('send_time/d');
        $input['red_type'] = Request::post('red_type');
        $input['account_id'] = Request::post('account_id/d');
        $input['can_rob'] = Request::post('can_rob');
        $input['num'] = Request::post('num/d');

        //模块 - 验证器
        $red_sendValidate = new \app\redenvelope\validate\RedSend;
        $validate = $red_sendValidate->scene('all_field')->check($input);
        if (!$validate) {
            $msg['msg'] = '验证失败';
            $msg['validate'] = $red_sendValidate->getError();
            return $this->errorJson($msg);
        }

        // ---	模块 - 修改  ---
        //更新的条件
        $update_date = [
            'id' => $input['id'],
        ];
        //更新的数据
        $update_map = [
            'amount' => $input['amount'],
            'message' => $input['message'],
            'send_time' => $input['send_time'],
            'red_type' => $input['red_type'],
            'account_id' => $input['account_id'],
            'can_rob' => $input['can_rob'],
            'num' => $input['num'],
        ];
        //获取数据
        $update_res = Db::name('red_send')->where($update_date)->update($update_map);
        if (!$update_res) {
            $msg['msg'] = '更新据失败！';
            return $this->errorJson($msg);
        }
        $msg['res'] = $update_res;


        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 按条件删除记录
     * @description 按条件删除发出红包列表的数据
     * @author 开发者（范浩婷）
     * @url /redenvelope/red_send/delete
     * @method post
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:Int require:1 default:0 other: desc:id
     * @param name:amount type:Int require:0 default:0 other: desc:金额
     * @param name:message type:VarChar require:0 default:0 other: desc:留言
     * @param name:send_time type:Int require:0 default:0 other: desc:发出红包的时间
     * @param name:red_type type:VarChar require:0 default:0 other: desc:红包的类型
     * @param name:account_id type:VarChar require:0 default:0 other: desc:发送人
     * @param name:can_rob type:decimal require:0 default:0 other: desc:红包可抢
     * @param name:num type:Int require:0 default:0 other: desc:红包的个数
     *
     *
     * @return id:id
     * @return amount:金额
     * @return message:留言
     * @return send_time:发出红包的时间
     * @return red_type:红包的类型
     * @return account_id:发送人
     * @return can_rob:红包可抢
     * @return num:红包的个数
     *
     */
    public function delete()
    {
        //模块 - 输入数据
        $input['id'] = Request::post('id/d');
        $input['amount'] = Request::post('amount');
        $input['message'] = Request::post('message');
        $input['send_time'] = Request::post('send_time/d');
        $input['red_type'] = Request::post('red_type');
        $input['account_id'] = Request::post('account_id/d');
        $input['can_rob'] = Request::post('can_rob');
        $input['num'] = Request::post('num/d');

        // ---  模块 - 删除  ---
        //删除的条件
        $temp_map = [
            ['id', '=', $input['id']],
            ['amount', '=', $input['amount']],
            ['message', '=', $input['message']],
            ['send_time', '=', $input['send_time']],
            ['red_type', '=', $input['red_type']],
            ['account_id', '=', $input['account_id']],
            ['can_rob', '=', $input['can_rob']],
            ['num', '=', $input['num']],
        ];
        $delete_map = [];
        foreach ($temp_map as $k => $v) {
            if ($v[2] == null || $v[2] == '') {
                continue;
            }
            array_push($delete_map, $v);
        }
        if (empty($delete_map)) {
            $msg['msg'] = '删除条件不能为空';
            return $this->errorJson($msg);
        }

        //删除数据
        $delete_res = Db::name('red_send')->where($delete_map)->delete();
        if (!$delete_res) {
            $msg['msg'] = '删除数据失败！';
            return $this->errorJson($msg);
        }
        $msg['res'] = $delete_res;

        //接口输出json数据
        $msg['msg'] = '操作成功！';
        return $this->successJson($msg);
    }

    /**
     * @title 指定id发送红包
     * @description 指定id发送红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/send_redpack_by_id
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:amount type:Int require:1 default:0 other: desc:金额
     * @param name:account_id type:VarChar require:1 default:0 other: desc:发送者
     * @param name:receive_id type:Int require:1 default:0 other: desc:接收者
     * @param name:message type:Varchar require:0 default:0 other: desc:留言
     *
     * @return amount:金额
     * @return message:留言
     * @return receive_id:接收者
     * @return account_id发送者
     */
    public function send_redpack_by_id()
    {

        $input['amount'] = Request::post('amount');
        $input['message'] = Request::post('message');
        $input['receive_id'] = Request::post('receive_id');
        $input['account_id']=Request::post('account_id');

        $validate = new Validate(
            $rules = [
                'amount' => 'require',
                'receive_id' => 'require',
                'account_id'=>'require'
            ]
        );
        if (!$validate->check($input)) {
            $msg['msg'] = '检验失败';
            $msg['validate'] = $validate->getError();
            return $this->errorJson($msg);
        }

        $insert_data = [
            'amount' => $input['amount'],
            'account_id'=>$input['account_id'],
            'receive_id' => $input['receive_id'],
            'num' => 1,
            'send_time' => time(),
            'message' => $input['message'],
            'red_type' => 'pt'
        ];

        if($input['amount']>1)
        {

            Db::name('red_send')->insert($insert_data);

            $msg['msg'] = "红包已发送";

            return $this->successJson($msg);

        } else {

            $msg['msg'] = "发送红包失败";

            return $this->errorJson($msg);
        }
    }

    /**
     * @title 发送平均包红包
     * @description 发送平均包红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/send_avg_pack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:amount type:Int require:1 default:0 other: desc:金额
     * @param name:num type:Int require:1 default:0 other: desc:红包的个数
     * @param name:account_id type:Varchar require:1 default:0 other: desc:发送者
     * @param name:can_rob type:Decimal require:0 default:0 other: desc:流水大于多少可抢
     * @param name:message type:Varchar require:0 default:0 other: desc:留言
     *
     *
     *
     * @return amount:金额
     * @return message:留言
     * @return can_rob:红包可抢
     * @return account_id:发送者
     * @return num:红包的个数
     * @return can_rob:流水大于多少可抢
     *
     */
    public function send_avg_pack()
    {
        $input['amount'] = Request::post('amount');
        $input['num'] = Request::post('num');
        $input['message'] = Request::post('message');
        $input['can_rob'] = Request::post('can_rob');
        $input['account_id']=Request::post('account_id');
        $validate = new Validate(
            $rules = [
                'amount' => 'require|integer',
                'num' => 'require|integer',
                'account_id'=>'require'
            ]
        );

        $insert_data = [
            'amount' => $input['amount'],
            'account_id'=>$input['account_id'],
            'send_time' => time(),
            'message' => $input['message'],
            'red_type'=>'avg',
            'num'=>$input['num'],
        ];

        if (!$validate->check($input)) {

            $msg['msg'] = '检验失败';

            $msg['validate'] = $validate->getError();

            return $this->errorJson($msg);
        }
            if($input['amount']>1)
            {

            Db::name('red_send')->insert($insert_data);

            $msg['msg'] = "红包已发送";

            return $this->successJson($msg);

        } else {

            $msg['msg'] = "红包发送失败";

            return $this->errorJson($msg);
        }

    }

    /**
     * @title 发送拼手气红包
     * @description 发送拼手气红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/send_pk_redpack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:amount type:Int require:1 default:0 other: desc:金额
     * @param name:num type:Int require:1 default:0 other: desc:红包的个数
     * @param name:account_id type:Varchar require:1 default:0 other: desc:发送者
     * @param name:can_rob type:Decimal require:0 default:0 other: desc:流水大于多少可抢
     * @param name:message type:Varchar require:0 default:0 other: desc:留言
     *
     *
     *
     * @return amount:金额
     * @return message:留言
     * @return account_id:发送者
     * @return num:红包的个数
     * @return can_rob:流水大于多少可抢
     *
     */
    public function send_pk_redpack()
    {
        $input['amount'] = Request::post('amount');
        $input['num'] = Request::post('num');
        $input['message'] = Request::post('message');
        $input['can_rob'] = Request::post('can_rob');
        $input['account_id']=Request::post('account_id');
        $validate = new Validate(
            $rules = [
                'amount' => 'require|integer',
                'num' => 'require|integer',
                'account_id'=>'require'
            ]
        );
        $insert_data = [
            'amount' => $input['amount'],
            'account_id'=>$input['account_id'],
            'send_time' => time(),
            'message' => $input['message'],
            'red_type' => 'pk',
            'num'=>$input['num'],
        ];

        if (!$validate->check($input)) {

            $msg['msg'] = '检验失败';

            $msg['validate'] = $validate->getError();

            return $this->errorJson($msg);
        }

        if($input['amount']>1)
        {

            Db::name('red_send')->insert($insert_data);

            $msg['msg'] = "红包已发送";

            return $this->successJson($msg);

        } else {

            $msg['msg'] = "红包发送失败";

            return $this->errorJson($msg);
        }

    }

    /**
     * @title 领取指定红包
     * @description 领取手气红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/receive_id_redpack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:receive_id type:Int require:0 default:0 other: desc:领取人
     * @param name:red_id type:Int require:0 default:0 other: desc:红包id
     *
     * @return receive_id:领取人
     * @return red_id:红包id
     */
     public function receive_id_redpack()
     {
         $input['red_id']=Request::post('red_id');

         $input['receive_id']=Request::post('receive_id');

         $result=Db::name('red_send')->where('id',$input['red_id'])->field('amount,send_time,receive_id')->find();

         $start_time=$result['send_time'];

         $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

         if(time() >= $start_time && time() <= $end_time)
         {
             $receive_lists = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

             if(is_null($receive_lists))
             {
                 $insert_temp = [
                     'amount' => $result['amount'],
                     'message' => '',
                     'receive_time' => time(),
                     'account_id' => '',
                     'red_id' => $input['red_id'],
                     'is_receive' => 1,
                     'receive_id'=>$result['receive_id']
                 ];
                 if($input['receive_id'] == $result['receive_id'])
                 {
                     Db::name('red_receive')->insert($insert_temp);

                     $receive_lists=Db::name('red_receive')->where('red_id',$input['red_id'])->find();

                     $msg['msg']="领取成功";

                     $msg['data']=$receive_lists;

                     return $this->successJson($msg);
                 }else{

                     $msg['msg']="领取失败";

                     return $this->errorJson($msg);
                 }
             }else{

                 $msg['msg']="您已经领取过该红包";

                 return $this->errorJson($msg);
             }


         }else{

             $msg['msg']="红包已过期";

             return $this->errorJson($msg);
         }

     }

    /**
     * @title 领取平均红包
     * @description 领取平均红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/receive_avg_redpack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:receive_id type:Int require:0 default:0 other: desc:领取人
     * @param name:red_id type:Int require:0 default:0 other: desc:红包id
     *
     * @return receive_id:领取人
     * @return red_id:红包id
     */
    public function receive_avg_redpack()
    {
        $input['receive_id'] = Request::post('receive_id');

        $input['red_id'] = Request::post('red_id');

        Db::startTrans();
        try {

            $result = Db::name('red_send')->where('id', $input['red_id'])->field('amount,num,send_time,account_id')->find();

            if (!$result) {

                Db::rollback();
                $msg['msg'] = '无发红包记录';
                return $this->errorJson($msg);
            }

            $total = $result['amount']; //总的金额

            $number = $result['num'];   //总的个数

            $current_num=Db::name('red_receive')->where("red_id",$input['red_id'])->count();  //已领取红包列表人数

                if($current_num == 0)
                {

                     Db::name('red_send')->where('id', $input['red_id'])->update(['res_num'=>$number,'res_money'=>$total]);

                     $res_money = $result['amount'];//红包金额初值

                     $res_num = $result['num']; //红包个数

                }else{

                    $do_result = Db::name('red_send')->where('id', $input['red_id'])->field('res_num,res_money')->find();

                    $res_money = $do_result['res_money'];//获取当前剩余红包金额

                    $res_num = $do_result['res_num']; //获取当前剩余红包的个数
                }

            $average = round($total / $number);

            $start_time = $result['send_time'];

            $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

            if ($res_num == 0) {

                $msg['msg'] = "您来晚了，红包已经抢完了";
                return $this->errorJson($msg);
            }
            switch (true) {
                case $total == 1 && $number == 1:
                    $msg['data']['num'] = 1;
                    $msg['data']['amount'] = 1;
                    $msg['data']['avg_num'][] = 1;
                    break;
                case $total == 1 && $number != 1:
                    $msg['msg'] = "钱不够所有人分";
                    break;
                case $total > 1 && $number != 1:
                    if ($total / $number < 1) {
                        $msg['msg'] = "钱不够所有人分";
                        return $this->errorJson($msg);
                    }
                    break;
            }

            if (time() >= $start_time && time() <= $end_time) {

                    $re = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

                    if (is_null($re)) { //无红包领取记录，领取红包

                        if ($res_num == 1) {
                            //剩余最后一个红包

                            $sum = Db::name('red_receive')->where('red_id',$input['red_id'])->sum('amount');

                            $average = $total - $sum;
                        }

                        $insert_temp = [
                            'amount' => $average,
                            'message' => '',
                            'receive_time' => time(),
                            'account_id' => $result['account_id'],
                            'red_id' => $input['red_id'],
                            'receive_id' => $input['receive_id'],
                            'is_receive' => 1

                        ];

                        Db::name('red_receive')->insert($insert_temp);

                        $res_num--;

                        $sub_red = $res_money - $average;

                        //更新发送红包表中的红包金额和数量
                        Db::name('red_send')->where(['id' => $input['red_id']])->update(['res_money' => $sub_red, 'res_num' => $res_num]);

                    } else {
                        Db::rollback();

                        $msg['msg'] = '你已经领取过该红包';

                        return $this->errorJson($msg);
                    }
//            for ($i = 0; $i < $num; $i++) {
//                //处理不能够平分的情况
//               $temp_arr[] = $average;
//
//            }
//            $arr = $temp_arr;
//
//            unset($arr[count($arr) - 1]);
//
//            $arr[count($temp_arr) - 1] = $res_money - array_sum($arr);
//
//            //领取之后数据保存在数据库知道哪个人领了多少红包,更新是否领取字段，领取的时间
//
//            for ($m=0;$m<count($arr);$i++)
//            {
//                for ($n=0;$n<$final_num;$n++)
//                {
//
//                }
//            }
                //领取之后数据保存在数据库知道哪个人领了多少红包,更新是否领取字段，领取的时
            } else {


                $msg['msg'] = "红包已过期";

                return $this->errorJson($msg);
            }

           //判断红包是否抢完修改rob_status状态

            $rob_num= Db::name('red_receive')->where('red_id',$input['red_id'])->count();

            if($rob_num < $number)
            {
                Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>0));
            }else{
                Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>1));
            }

            $receives_lists = Db::name('red_receive')->where('red_id', $input['red_id'])->select();

            $msg['data']['list'] = $receives_lists;

            $msg['msg'] = "红包领取成功";

            Db::commit();

            return $this->successJson($msg);

        } catch (\Exception $e) {
            Db::rollback();
            $msg['msg'] = $e->getMessage();
            return $this->errorJson($msg);

        }
    }

    /**
     * @title 领取拼手气红包
     * @description 领取拼手气红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/receive_pk_redpack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:receive_id type:Int require:0 default:0 other: desc:领取人
     * @param name:red_id type:Int require:0 default:0 other: desc:红包id
     *
     * @return receive_id:领取人
     * @return red_id:红包id
     */
    public function receive_pk_redpack()
    {

        $input['receive_id']=Request::post('receive_id');

        $input['red_id']=Request::post('red_id');

        Db::startTrans();
        try{

//        $input['amount'] = $input['amount'] * 100;// (换算单位为分)

            $result = Db::name('red_send')->where('id', $input['red_id'])->field('amount,num,send_time')->find();

            if (!$result) {

                Db::rollback();
                $msg['msg'] = '无发红包记录';
                return $this->errorJson($msg);
            }

            $total = $result['amount']; //总的金额

            $number = $result['num'];   //总的个数

            $current_num=Db::name('red_receive')->where("red_id",$input['red_id'])->count();  //已领取红包列表人数

            if($current_num == 0)
            {

                Db::name('red_send')->where('id', $input['red_id'])->update(['res_num'=>$number,'res_money'=>$total]);

                $res_money = $result['amount'];//红包金额初值

                $res_num = $result['num']; //红包个数

            }else{

                $do_result = Db::name('red_send')->where('id', $input['red_id'])->field('res_num,res_money')->find();

                $res_money = $do_result['res_money'];//获取当前剩余红包金额

                $res_num = $do_result['res_num']; //获取当前剩余红包的个数
            }

//            $average = round($total / $number);

            $start_time = $result['send_time'];

            $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

            if ($res_num == 0) {

                $msg['msg'] = "您来晚了，红包已经抢完了";
                return $this->errorJson($msg);
            }

//            $arr_sum = 0; //保存数组和

            switch (true) {
                case $total == 1 && $number == 1:
                    $msg['data']['num'] = 1;
                    $msg['data']['amount'] = 1;
                    $msg['data']['avg_num'][] = 1;
                    break;
                case $total == 1 && $number != 1:
                    $msg['msg'] = "钱不够所有人分";
                    break;
                case $total > 1 && $number != 1:
                    if ($total / $number < 1) {
                        $msg['msg'] = "钱不够所有人分";
                        return $this->errorJson($msg);
                    }
                    break;
            }

            if(time() >= $start_time && time() <= $end_time)
            {
                $re = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

                if(is_null($re))
                {
                    //不存在领取记录可以领取红包

                    $range_money = round($res_money / $res_num);

                    $rand_money=mt_rand(1,$range_money);

                    if ($res_num == 1) {
                        //剩余最后一个红包

                        $sum = Db::name('red_receive')->where('red_id',$input['red_id'])->sum('amount');

                        $rand_money = $total - $sum;
                    }

                    $insert_temp = [
                        'amount' => $rand_money,
                        'message' => '',
                        'receive_time' => time(),
                        'account_id' => '',
                        'red_id' => $input['red_id'],
                        'receive_id' => $input['receive_id'],
                        'is_receive' => 1

                    ];

                    Db::name('red_receive')->insert($insert_temp);

                    $res_num--;

                    $sub_red = $res_money - $rand_money;

                    Db::name('red_send')->where(['id' => $input['red_id']])->update(['res_money' => $sub_red, 'res_num' => $res_num]);

                }else{

                    Db::rollback();

                    $msg['msg']="你已经领取过该红包";

                    return $this->errorJson($msg);
                }
//                //随机分配
//                for ($i = 0; $i < $number; $i++) {
//
//                    $range_money = round(($res_money / ($number - $i)));
//
//                    $rand_money = mt_rand(1, $range_money);
//
//                    $arr[] = $rand_money;
//
//                    $res_money = $res_money - $rand_money;   //循环获取每次剩下的钱
//
//                }
//
//                if (count($arr) > 0) {
//                    foreach ($arr as $k => $v) {
//
//                        $arr_sum = array_sum($arr);   //计算已随机分配的红包总额
//
//                    }
//                } else {
//                    for ($i = 0; $i < $number; $i++) {
//
//                        $arr[] = 0;      // 初始化每个人的数组，兼容下边循环处理部分
//
//                    }
//                }
//                //分配剩余的红包
//                $res_money = $total - $arr_sum;
//
//                if ($res_money == 0) {
//
//                    $msg['msg'] = "您来晚了，红包已经抢完了";
//
//                    return $this->errorJson($msg);
//
//                }
//                for ($i = 0; $i < $number; $i++) {
//
//                    $arr[$i] = $arr[$i] + floor($res_money / $number);
//
//                }
//
//                $arr_sum = array_sum($arr);
//
//                $final_money = bcsub($total, $arr_sum, 0);
//
//                $i = 0;
//
//                while ($final_money >= 1) {
//
//                    $arr[$i] = $arr[$i] + 1;
//
//                    $final_money = $final_money - 1;
//
//                    $i++;
            }else{
                $msg['msg']="红包已过期";

                return $this->errorJson($msg);
            }
            $receives_lists = Db::name('red_receive')->where('red_id', $input['red_id'])->select();

            $msg['data']['list'] = $receives_lists;

            $msg['msg'] = "红包领取成功";

            Db::commit();

            return $this->successJson($msg);

        }catch (\Exception $e)
        {
            $msg['msg']=$e->getMessage();

            return $this->errorJson($msg);
        }
    }

    /**
     * @title 领取红包
     * @description 领取红包
     * @author  开发者（范浩婷）
     * @url /redenvelope/red_send/receive_redpack
     * @method post
     *
     * @param name:token require:1 default: desc:token
     * @param name:receive_id type:Int require:1 default:0 other: desc:领取人
     * @param name:red_id type:Int require:1 default:0 other: desc:红包id
     *
     * @return receive_id:领取人
     * @return red_id:红包id
     */
    public function receive_redpack()
    {
        $input['receive_id']=Request::post('receive_id');

        $input['red_id']=Request::post('red_id');

        Db::startTrans();
        try{
            $result= Db::name('red_send')->where('id',$input['red_id'])->field('red_type')->find();
            //领取平均红包
            if($result['red_type']=='avg')
            {
                $result = Db::name('red_send')->where('id', $input['red_id'])->field('amount,num,send_time,account_id')->find();

                if (!$result) {

                    Db::rollback();
                    $msg['msg'] = '无发红包记录';
                    return $this->errorJson($msg);
                }

                $total = $result['amount']; //总的金额

                $number = $result['num'];   //总的个数

                $current_num=Db::name('red_receive')->where("red_id",$input['red_id'])->count();  //已领取红包列表人数

                if($current_num == 0)
                {

                    Db::name('red_send')->where('id', $input['red_id'])->update(['res_num'=>$number,'res_money'=>$total]);

                    $res_money = $result['amount'];//红包金额初值

                    $res_num = $result['num']; //红包个数

                }else{

                    $do_result = Db::name('red_send')->where('id', $input['red_id'])->field('res_num,res_money')->find();

                    $res_money = $do_result['res_money'];//获取当前剩余红包金额

                    $res_num = $do_result['res_num']; //获取当前剩余红包的个数
                }

                $average = round($total / $number);

                $start_time = $result['send_time'];

                $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

                if ($res_num == 0) {

                    $msg['msg'] = "您来晚了，红包已经抢完了";
                    return $this->errorJson($msg);
                }
                switch (true) {
                    case $total == 1 && $number == 1:
                        $msg['data']['num'] = 1;
                        $msg['data']['amount'] = 1;
                        $msg['data']['avg_num'][] = 1;
                        break;
                    case $total == 1 && $number != 1:
                        $msg['msg'] = "钱不够所有人分";
                        break;
                    case $total > 1 && $number != 1:
                        if ($total / $number < 1) {
                            $msg['msg'] = "钱不够所有人分";
                            return $this->errorJson($msg);
                        }
                        break;
                }

                if (time() >= $start_time && time() <= $end_time) {

                    $re = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

                    if (is_null($re)) { //无红包领取记录，领取红包

                        if ($res_num == 1) {
                            //剩余最后一个红包

                            $sum = Db::name('red_receive')->where('red_id',$input['red_id'])->sum('amount');

                            $average = $total - $sum;
                        }

                        $insert_temp = [
                            'amount' => $average,
                            'message' => '',
                            'receive_time' => time(),
                            'account_id' => $result['account_id'],
                            'red_id' => $input['red_id'],
                            'receive_id' => $input['receive_id'],
                            'is_receive' => 1

                        ];

                        Db::name('red_receive')->insert($insert_temp);

                        $res_num--;

                        $sub_red = $res_money - $average;

                        //更新发送红包表中的红包金额和数量
                        Db::name('red_send')->where(['id' => $input['red_id']])->update(['res_money' => $sub_red, 'res_num' => $res_num]);

                    } else {
                        Db::rollback();

                        $msg['msg'] = '你已经领取过该红包';

                        return $this->errorJson($msg);
                    }

                } else {


                    $msg['msg'] = "红包已过期";

                    return $this->errorJson($msg);
                }

                //判断红包是否抢完修改rob_status状态

                $rob_num= Db::name('red_receive')->where('red_id',$input['red_id'])->count();

                if($rob_num < $number)
                {
                    Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>0));
                }else{
                    Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>1));
                }

                $receives_lists = Db::name('red_receive')->where('red_id', $input['red_id'])->select();

                $msg['data']['list'] = $receives_lists;

                $msg['msg'] = "红包领取成功";

                Db::commit();

                return $this->successJson($msg);

        }elseif ($result['red_type']=='pk'){

                //领取拼手气红包
                $result = Db::name('red_send')->where('id', $input['red_id'])->field('amount,num,send_time,account_id')->find();

                if (!$result) {

                    Db::rollback();
                    $msg['msg'] = '无发红包记录';
                    return $this->errorJson($msg);
                }

                $total = $result['amount']; //总的金额

                $number = $result['num'];   //总的个数

                $current_num=Db::name('red_receive')->where("red_id",$input['red_id'])->count();  //已领取红包列表人数

                if($current_num == 0)
                {

                    Db::name('red_send')->where('id', $input['red_id'])->update(['res_num'=>$number,'res_money'=>$total]);

                    $res_money = $result['amount'];//红包金额初值

                    $res_num = $result['num']; //红包个数

                }else{

                    $do_result = Db::name('red_send')->where('id', $input['red_id'])->field('res_num,res_money')->find();

                    $res_money = $do_result['res_money'];//获取当前剩余红包金额

                    $res_num = $do_result['res_num']; //获取当前剩余红包的个数
                }

//            $average = round($total / $number);

                $start_time = $result['send_time'];

                $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

                if ($res_num == 0) {

                    $msg['msg'] = "您来晚了，红包已经抢完了";
                    return $this->errorJson($msg);
                }

//            $arr_sum = 0; //保存数组和

                switch (true) {
                    case $total == 1 && $number == 1:
                        $msg['data']['num'] = 1;
                        $msg['data']['amount'] = 1;
                        $msg['data']['avg_num'][] = 1;
                        break;
                    case $total == 1 && $number != 1:
                        $msg['msg'] = "钱不够所有人分";
                        break;
                    case $total > 1 && $number != 1:
                        if ($total / $number < 1) {
                            $msg['msg'] = "钱不够所有人分";
                            return $this->errorJson($msg);
                        }
                        break;
                }

                if(time() >= $start_time && time() <= $end_time)
                {
                    $re = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

                    if(is_null($re))
                    {
                        //不存在领取记录可以领取红包

                        $range_money = round($res_money / $res_num);

                        $rand_money=mt_rand(1,$range_money);

                        if ($res_num == 1) {
                            //剩余最后一个红包

                            $sum = Db::name('red_receive')->where('red_id',$input['red_id'])->sum('amount');

                            $rand_money = $total - $sum;
                        }

                        $insert_temp = [
                            'amount' => $rand_money,
                            'message' => '',
                            'receive_time' => time(),
                            'account_id' => $result['account_id'],
                            'red_id' => $input['red_id'],
                            'receive_id' => $input['receive_id'],
                            'is_receive' => 1

                        ];

                        Db::name('red_receive')->insert($insert_temp);

                        $res_num--;

                        $sub_red = $res_money - $rand_money;

                        Db::name('red_send')->where(['id' => $input['red_id']])->update(['res_money' => $sub_red, 'res_num' => $res_num]);

                    }else{

                        Db::rollback();

                        $msg['msg']="你已经领取过该红包";

                        return $this->errorJson($msg);
                    }
//                //随机分配
//                for ($i = 0; $i < $number; $i++) {
//
//                    $range_money = round(($res_money / ($number - $i)));
//
//                    $rand_money = mt_rand(1, $range_money);
//
//                    $arr[] = $rand_money;
//
//                    $res_money = $res_money - $rand_money;   //循环获取每次剩下的钱
//
//                }
//
//                if (count($arr) > 0) {
//                    foreach ($arr as $k => $v) {
//
//                        $arr_sum = array_sum($arr);   //计算已随机分配的红包总额
//
//                    }
//                } else {
//                    for ($i = 0; $i < $number; $i++) {
//
//                        $arr[] = 0;      // 初始化每个人的数组，兼容下边循环处理部分
//
//                    }
//                }
//                //分配剩余的红包
//                $res_money = $total - $arr_sum;
//
//                if ($res_money == 0) {
//
//                    $msg['msg'] = "您来晚了，红包已经抢完了";
//
//                    return $this->errorJson($msg);
//
//                }
//                for ($i = 0; $i < $number; $i++) {
//
//                    $arr[$i] = $arr[$i] + floor($res_money / $number);
//
//                }
//
//                $arr_sum = array_sum($arr);
//
//                $final_money = bcsub($total, $arr_sum, 0);
//
//                $i = 0;
//
//                while ($final_money >= 1) {
//
//                    $arr[$i] = $arr[$i] + 1;
//
//                    $final_money = $final_money - 1;
//
//                    $i++;
                }else{
                    $msg['msg']="红包已过期";

                    return $this->errorJson($msg);
                }

                //判断红包是否抢完修改rob_status状态

                $rob_num= Db::name('red_receive')->where('red_id',$input['red_id'])->count();

                if($rob_num < $number)
                {
                    Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>0));
                }else{
                    Db::name('red_send')->where('id',$input['red_id'])->update(array('rob_status'=>1));
                }

                $receives_lists = Db::name('red_receive')->where('red_id', $input['red_id'])->select();

                $msg['data']['list'] = $receives_lists;

                $msg['msg'] = "红包领取成功";

                Db::commit();

                return $this->successJson($msg);

            }
            else{
                //领取指定的ID领取红包

                $result=Db::name('red_send')->where('id',$input['red_id'])->field('amount,send_time,receive_id,account_id')->find();

                $start_time=$result['send_time'];

                $end_time = strtotime(date('Y-m-d H:i:s', $start_time + (1 * 24 * 60 * 60)));

                if(time() >= $start_time && time() <= $end_time)
                {
                    $receive_lists = Db::name('red_receive')->where(['red_id' => $input['red_id'], 'receive_id' => $input['receive_id']])->find();

                    if(is_null($receive_lists))
                    {
                        $insert_temp = [
                            'amount' => $result['amount'],
                            'message' => '',
                            'receive_time' => time(),
                            'account_id' => $result['account_id'],
                            'red_id' => $input['red_id'],
                            'is_receive' => 1,
                            'receive_id'=>$result['receive_id']
                        ];
                        if($input['receive_id'] == $result['receive_id'])
                        {
                            Db::name('red_receive')->insert($insert_temp);

                            $receive_lists=Db::name('red_receive')->where('red_id',$input['red_id'])->find();

                            $msg['msg']="领取成功";

                            Db::commit();

                            $msg['data']=$receive_lists;

                            return $this->successJson($msg);
                        }else{

                            $msg['msg']="领取失败";

                            return $this->errorJson($msg);
                        }
                    }else{

                        Db::rollback();

                        $msg['msg']="您已经领取过该红包";

                        return $this->errorJson($msg);
                    }

                }else{

                    $msg['msg']="红包已过期";

                    return $this->errorJson($msg);
                }
            }
        }catch (\Exception $e){

            $msg['msg']=$e->getMessage();

            return $this->errorJson($msg);
        }

    }
}


